import 'package:get/get.dart';

import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:meco/common/index.dart';

class ShareController extends GetxController
    implements CeramicInteractionObserver, CeramicDeleteObserver {
  ShareController();

  final CeramicRepository _ceramicRepository = CeramicRepository();
  final UserRepository _userRepository = UserRepository();
  final UserFollowRepository _userFollowRepository = UserFollowRepository();
  final CeramicInteractionRepository _interactionRepository =
      CeramicInteractionRepository();
  final ChatRoomRepository _chatRoomRepository = ChatRoomRepository();

  final RxList<Ceramic> completedCeramics = <Ceramic>[].obs;
  final RxBool isLoading = true.obs;
  final RxList<ChatRoom> groupChats = <ChatRoom>[].obs;
  final RxMap<int, User> chatUserCache = <int, User>{}.obs;

  // 用户信息缓存
  final RxMap<int, User> userCache = <int, User>{}.obs;
  // 用户关注状态缓存
  final RxMap<int, bool> followStatusCache = <int, bool>{}.obs;
  // 当前用户ID (假设已登录用户的ID)
  final int currentUserId = 1; // 这里应该从用户会话中获取
  // 点赞状态
  final RxMap<int, bool> likeStatusCache = <int, bool>{}.obs;
  // 收藏状态
  final RxMap<int, bool> favoriteStatusCache = <int, bool>{}.obs;

  _initData() async {
    await _loadCompletedCeramics();
    await _loadGroupChats();
    update(["share"]);
  }

  // 加载群聊数据
  Future<void> _loadGroupChats() async {
    try {
      // 获取所有群聊房间
      final db = await Get.find<DatabaseService>().database;
      final List<Map<String, dynamic>> maps = await db.query(
        'chat_rooms',
        where: 'is_group = ?',
        whereArgs: [1], // 1代表是群聊
      );

      // 转换为ChatRoom对象
      List<ChatRoom> rooms = maps.map((map) => ChatRoom.fromJson(map)).toList();

      // 筛选出成员数量较多的群聊作为热门群聊
      rooms.sort((a, b) => b.memberIds.length.compareTo(a.memberIds.length));
      groupChats.value = rooms;

      // 预加载群聊成员数据
      for (var room in groupChats) {
        for (var userId in room.memberIds) {
          await _loadChatUserData(userId);
        }
      }
    } catch (e) {
      print('加载群聊数据失败: $e');
    }
  }

  // 加载群聊用户数据
  Future<User?> _loadChatUserData(int userId) async {
    if (chatUserCache.containsKey(userId)) {
      return chatUserCache[userId];
    }

    try {
      final user = await _userRepository.getUserById(userId);
      if (user != null) {
        chatUserCache[userId] = user;
      }
      return user;
    } catch (e) {
      print('加载群聊用户数据失败: $e');
      return null;
    }
  }

  // 加入群聊
  Future<void> joinGroupChat(int chatRoomId) async {
    final userService = Get.find<UserService>();

    await userService.checkLoginThenExecute(
      onLoggedIn: () async {
        try {
          // 获取当前登录用户
          final currentUserId = userService.currentUser.value?.id;
          if (currentUserId == null) return;

          // 获取群聊
          final chatRoom = await _chatRoomRepository.getChatRoomById(
            chatRoomId,
          );
          if (chatRoom == null) return;

          // 检查用户是否已经在群聊中
          if (chatRoom.memberIds.contains(currentUserId)) {
            // 用户已在群聊中，直接跳转到聊天页面
            Get.toNamed(Routes.chat, arguments: {'chatRoom': chatRoom});
            return;
          }

          // 添加用户到群聊
          List<int> newMemberIds = List.from(chatRoom.memberIds);
          newMemberIds.add(currentUserId);

          // 更新群聊
          final updatedChatRoom = chatRoom.copyWith(
            memberIds: newMemberIds,
            updatedAt: DateTime.now(),
          );

          await _chatRoomRepository.updateChatRoom(updatedChatRoom);
          EasyLoading.showSuccess('Joined successfully');

          // 刷新群聊数据
          await _loadGroupChats();

          // 加入群聊后，跳转到该群聊的聊天页面
          Get.toNamed(Routes.chat, arguments: {'chatRoom': updatedChatRoom});
        } catch (e) {
          print('加入群聊失败: $e');
          EasyLoading.showError('Failed to join');
        }
      },
      loginRequiredMessage: 'Login required to join group chat',
    );
  }

  // 加载已完成或跳过烧制的陶瓷作品
  Future<void> _loadCompletedCeramics() async {
    isLoading.value = true;
    try {
      // 获取所有陶瓷作品
      List<Ceramic> allCeramics = await _ceramicRepository.getAllCeramics();

      // 筛选已完成或跳过烧制的陶瓷作品
      completedCeramics.value =
          allCeramics
              .where((ceramic) => ceramic.isCompleted || ceramic.isSkipped)
              .toList();

      // 预加载用户数据、关注状态和交互状态
      for (var ceramic in completedCeramics) {
        await loadUserData(ceramic.userId);
        await checkFollowStatus(ceramic.userId);
        await checkLikeStatus(ceramic.id!);
        await checkFavoriteStatus(ceramic.id!);
      }
    } catch (e) {
      print('加载陶瓷作品失败: $e');
    } finally {
      isLoading.value = false;
    }
  }

  // 加载用户数据
  Future<User?> loadUserData(int userId) async {
    if (userCache.containsKey(userId)) {
      return userCache[userId];
    }

    try {
      final user = await _userRepository.getUserById(userId);
      if (user != null) {
        userCache[userId] = user;
      }
      return user;
    } catch (e) {
      print('加载用户数据失败: $e');
      return null;
    }
  }

  // 检查关注状态
  Future<bool> checkFollowStatus(int userId) async {
    if (followStatusCache.containsKey(userId)) {
      return followStatusCache[userId]!;
    }

    try {
      final isFollowing = await _userFollowRepository.isFollowing(
        currentUserId,
        userId,
      );
      followStatusCache[userId] = isFollowing;
      return isFollowing;
    } catch (e) {
      print('检查关注状态失败: $e');
      followStatusCache[userId] = false;
      return false;
    }
  }

  // 关注/取消关注用户
  Future<void> toggleFollow(int userId) async {
    final isFollowing = followStatusCache[userId] ?? false;

    try {
      if (isFollowing) {
        await _userFollowRepository.unfollowUser(
          followerId: currentUserId,
          followingId: userId,
        );
        followStatusCache[userId] = false;
      } else {
        await _userFollowRepository.followUser(
          followerId: currentUserId,
          followingId: userId,
        );
        followStatusCache[userId] = true;
      }
      update(["share"]);
    } catch (e) {
      print('切换关注状态失败: $e');
    }
  }

  // 检查点赞状态
  Future<bool> checkLikeStatus(int ceramicId) async {
    if (likeStatusCache.containsKey(ceramicId)) {
      return likeStatusCache[ceramicId]!;
    }

    try {
      final hasLiked = await _interactionRepository.hasLiked(
        currentUserId,
        ceramicId,
      );
      likeStatusCache[ceramicId] = hasLiked;
      return hasLiked;
    } catch (e) {
      print('检查点赞状态失败: $e');
      likeStatusCache[ceramicId] = false;
      return false;
    }
  }

  // 点赞/取消点赞
  Future<void> toggleLike(int ceramicId) async {
    final isLiked = likeStatusCache[ceramicId] ?? false;

    try {
      if (isLiked) {
        await _interactionRepository.unlikeCeramic(currentUserId, ceramicId);
        likeStatusCache[ceramicId] = false;
      } else {
        await _interactionRepository.likeCeramic(currentUserId, ceramicId);
        likeStatusCache[ceramicId] = true;
      }
      // 重新加载陶瓷信息以更新点赞数
      await _refreshCeramicData(ceramicId);
      update(["share"]);
    } catch (e) {
      print('切换点赞状态失败: $e');
    }
  }

  // 检查收藏状态
  Future<bool> checkFavoriteStatus(int ceramicId) async {
    if (favoriteStatusCache.containsKey(ceramicId)) {
      return favoriteStatusCache[ceramicId]!;
    }

    try {
      final hasFavorited = await _interactionRepository.hasFavorited(
        currentUserId,
        ceramicId,
      );
      favoriteStatusCache[ceramicId] = hasFavorited;
      return hasFavorited;
    } catch (e) {
      print('检查收藏状态失败: $e');
      favoriteStatusCache[ceramicId] = false;
      return false;
    }
  }

  // 收藏/取消收藏
  Future<void> toggleFavorite(int ceramicId) async {
    final isFavorited = favoriteStatusCache[ceramicId] ?? false;

    try {
      if (isFavorited) {
        await _interactionRepository.unfavoriteCeramic(
          currentUserId,
          ceramicId,
        );
        favoriteStatusCache[ceramicId] = false;
      } else {
        await _interactionRepository.favoriteCeramic(currentUserId, ceramicId);
        favoriteStatusCache[ceramicId] = true;
      }
      // 重新加载陶瓷信息以更新收藏数
      await _refreshCeramicData(ceramicId);
      update(["share"]);
    } catch (e) {
      print('切换收藏状态失败: $e');
    }
  }

  // 刷新陶瓷数据
  Future<void> _refreshCeramicData(int ceramicId) async {
    try {
      final ceramic = await _ceramicRepository.getCeramicById(ceramicId);
      if (ceramic != null) {
        final index = completedCeramics.indexWhere((c) => c.id == ceramicId);
        if (index != -1) {
          completedCeramics[index] = ceramic;
        }
      }
    } catch (e) {
      print('刷新陶瓷数据失败: $e');
    }
  }

  void onTap() {}

  @override
  void onInit() {
    super.onInit();
    // 注册为观察者，接收陶瓷交互状态更新
    CeramicInteractionRepository.addObserver(this);
    // 注册为观察者，接收陶瓷删除通知
    CeramicRepository.addObserver(this);
  }

  @override
  void onClose() {
    super.onClose();
    // 取消注册观察者
    CeramicInteractionRepository.removeObserver(this);
    CeramicRepository.removeObserver(this);
  }

  // 实现CeramicInteractionObserver接口
  @override
  void onLikeStatusChanged(int userId, int ceramicId, bool isLiked) {
    // 更新本地状态缓存
    likeStatusCache[ceramicId] = isLiked;

    // 更新陶瓷作品的点赞数
    final index = completedCeramics.indexWhere((c) => c.id == ceramicId);
    if (index != -1) {
      final ceramic = completedCeramics[index];
      completedCeramics[index] = ceramic.copyWith(
        likeCount: isLiked ? ceramic.likeCount + 1 : ceramic.likeCount - 1,
      );
      update(["share"]);
    }
  }

  @override
  void onFavoriteStatusChanged(int userId, int ceramicId, bool isFavorited) {
    // 更新本地状态缓存
    favoriteStatusCache[ceramicId] = isFavorited;

    // 更新陶瓷作品的收藏数
    final index = completedCeramics.indexWhere((c) => c.id == ceramicId);
    if (index != -1) {
      final ceramic = completedCeramics[index];
      completedCeramics[index] = ceramic.copyWith(
        favoriteCount:
            isFavorited ? ceramic.favoriteCount + 1 : ceramic.favoriteCount - 1,
      );
      update(["share"]);
    }
  }

  @override
  void onReady() {
    super.onReady();
    _initData();
  }

  // 实现CeramicDeleteObserver接口
  @override
  void onCeramicDeleted(int ceramicId) {
    // 从列表中移除被删除的陶瓷作品
    completedCeramics.removeWhere((ceramic) => ceramic.id == ceramicId);
    update(["share"]);
  }
}
